package com.base.monitor.module.biz.message.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.base.monitor.model.constant.CfgConstant;
import com.base.monitor.model.constant.CollectConstant;
import com.base.monitor.model.model.biz.cfg.entity.Gateway;
import com.base.monitor.model.model.biz.cfg.entity.Indicator;
import com.base.monitor.module.biz.context.CfgContext;
import com.base.monitor.module.biz.context.ClientContext;
import com.base.monitor.module.biz.message.Message;
import com.base.monitor.module.biz.util.ChannelUtils;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class ConnectMessage implements Message {
    /**
     * 消息类型
     *
     * @return
     */
    @Override
    public String messageType() {
        return CollectConstant.MESSAGE_TYPE_IS_CONNECT;
    }

    /**
     * 处理消息
     * @param ctx netty客户端通道信息
     * @param message 消息内容
     */
    @Override
    public void handle(ChannelHandlerContext ctx, String message) {
        log.info("处理ip为{}的连接消息，消息内容为{}", ctx.channel().remoteAddress(), message);

        // 1.获取信道ip
        String rawIp = ctx.channel().remoteAddress().toString();

        // 2.根据连接命令获取网关的信息
        Gateway gateway = CfgContext.getGatewayVoByCommand(message.substring(0, 8));
        if (gateway == null) {
            log.error("=== " + rawIp + " is not allowed to connect the server because it isn't exists in sync data ===");
            ctx.close();
            return;
        }

        // 3.获取网关类型
        Integer type = gateway.getGatewayType();

        // 4.判断是否可以连接
        if (type.equals(CfgConstant.NORMAL_GATEWAY)
                && !gateway.getGatewayIp().equals(ChannelUtils.formatChannelIp(rawIp))) {
            log.error("=== " + rawIp + " is not allowed to connect the server because it " +
                    "is normal gateway and channel ip is not equals configured ip ===");
            ctx.close();
            return;
        }
        if (!ClientContext.canConnect(message)) {
            log.error("=== " + rawIp + " is not allowed to connect the server by blacklist ===");
            ctx.close();
            return;
        }
        log.error("=== " + rawIp + " is active ===");

        // 5.如果是4g网关要修改CfgContext中对应记录的ip地址
        if (type.equals(CfgConstant.G4_GATEWAY)) {
            String ip = ChannelUtils.formatChannelIp(rawIp);
            // 修改网关ip
            gateway.setGatewayIp(ip);
            // 修改指标ip
            List<Indicator> indicators = CfgContext.getIndicatorAllVoListByGatewayId(gateway.getGatewayId());
            if (CollectionUtil.isEmpty(indicators)) {
                return;
            }
            indicators.forEach(item -> item.setGatewayIp(ip));
        }

        // 6.将信道实例保存起来
        ClientContext.addClient(message, ctx);

        // 7.修改在线时间
        CfgContext.addGatewayOnlineTime(gateway.getGatewayId());
    }
}
